# 1.导包
import os
os.environ['OMP_NUM_THREADS'] = '4'

from sklearn.datasets import make_blobs     # 随机参数样本数据
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans          # KMeans算法
from sklearn.metrics import calinski_harabasz_score     # 轮廓系数

# 2.准备数据
x_data, y_data = make_blobs(
    n_samples=1000,
    n_features=4,
    cluster_std=[0.3, 0.2, 0.3, 0.2],
    centers=[[0, 0], [1, 1], [2, 2], [3, 3]],
    random_state=929
)

# 2.1 回绘制样本的散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()


# 3.特征工程
# 3.1 模型构建
model = KMeans(n_clusters=4)

# 3.2 模型预测
y_pre = model.fit_predict(x_data)

# 3.3 散点图绘制
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_pre)
plt.title("KMeans")
plt.show()

# 4.模型评估
print(f"原始样本的轮廓系数：{calinski_harabasz_score(x_data,y_data)}")
print(f"聚类预测后的轮廓系数：{calinski_harabasz_score(x_data,y_pre)}")